package no.ffi.gismoidm.pubsub;

import no.fongen.os.FIFO;

/**
 * Class represents a node with message router responsibility. There are
 * objects of this class for every MR in the system, not only the neighbors
 * 
 * @author anders
 */
public class MessageRouter extends MessageNeighbor {
    
    private transient ForwardingTable forwardingTable;
    // Public constructor
    public MessageRouter(String mrId, FIFO outward, String myId) {
        messageNeighborID = mrId;
        outwardMessages = outward;
        forwardingTable = ForwardingTable.getInstance();
        System.out.println("New Message Router connected, id="+messageNeighborID);
        forwardingTable.setNeighborEntry(mrId,this);
        forwardingTable.aggregateSubscriptionReceived(new AggregateSubscription(mrId), this);
    }
    
    @Override
    public void receiveMessage(Object message) {
        // Message can be an AggSub message or a publication
        if (message instanceof AggregateSubscription) {
            AggregateSubscription aggSub = (AggregateSubscription)message;
            // Pass it to the forwardTable object for processing
            forwardingTable.aggregateSubscriptionReceived(aggSub, this);
        } else if (message instanceof Publication) {
            Publication pub = (Publication)message;
            forwardingTable.publicationReceived(pub, this);
        }
    }
    
    public void terminateClient() {
        System.out.println("Terminating connection to MessageRouter peer " + messageNeighborID);
        forwardingTable.removeNeighbor(messageNeighborID);
    }

}
